﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;

namespace ImageUploaderComponent
{
    public partial class ImageDisplay : IDisposable
    {
        private const int Offset = 50;

        public ImageDisplay()
        {
            InitializeComponent();
        }

        public Byte[] ImageBytes
        {
            set
            {
                setImageDisplay(value);
            }
        }


        private byte[] imageBytes;


        public void ShowYerself(Point pointOfHover,Size newSize)
        {
            BitmapImage bmp = new ImageHelper().GetBmpFromBytes(imageBytes);
            TheImage.Source = bmp;
            TheImage.Width = newSize.Width;
            TheImage.Height = newSize.Height;
            WidthAnimation.To = newSize.Width;
            HeightAnimation.To = newSize.Height;
            ClipGeometry.Rect = new Rect(0, 0, newSize.Width - 5, newSize.Height - 5);
            ClipGeometry.RadiusX = 10;
            ClipGeometry.RadiusY = 10;

            Point upperLeft = computeUpperLeft(pointOfHover, newSize);
            Canvas.SetLeft(this, upperLeft.X);
            Canvas.SetTop(this, upperLeft.Y);
        }

        private Point computeUpperLeft(Point pointOfHover, Size newSize){
            double y;
            if (newSize.Height <= Offset)
            {
                y = pointOfHover.Y - 20;
            }
            else
            {
                y = pointOfHover.Y - newSize.Height + Offset;
                if (y < 0)
                {
                    y = 10;
                }
            }


            double x;
            if (newSize.Width <= Offset)
            {
                x = pointOfHover.X - Offset;
            }
            else
            {
                x = pointOfHover.X - newSize.Width + Offset;
                if (x < 0)
                {
                    x = 10;
                }
            }
            return  new Point(x,y);
        }

        private void setImageDisplay(Byte[] imageBytes)
        {
            if (imageBytes == null)
            {
                Width = 200;
                Height = 100;
            }
            else
            {
                DataContext = imageBytes;
                this.imageBytes = imageBytes;


            }
        }



        ~ImageDisplay()
        {
            TheImage = null;
        }








        public void Dispose()
        {
            TheImage.Source = null;
            LayoutRoot.Children.Remove(TheImage);

        }


    }
}
